package com.zzyk.microCloud.Quartz;



import cn.hutool.cron.CronUtil;
import cn.hutool.cron.task.Task;
import com.zzyk.main.service.MaintenanceInfoService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author wss_PC
 * @DESCRIPTION 当项目执行时执行的类
 * @create 2020-6-10 11:57
 */
@Component("StartupListener")
@Log4j2
public class InitListener implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    private MaintenanceInfoService service;

    /**
     * 当项目启动时调用这个方法
     * timer.schedule(task, 0); // 此处delay为0表示没有延迟，立即执行一次task
     * timer.schedule(task, 1000); // 延迟1秒，执行一次task
     * timer.schedule(task, 0, 2000); // 立即执行一次task，然后每隔2秒执行一次task
     *
     * @param contextRefreshedEvent
     */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        if (contextRefreshedEvent.getApplicationContext().getParent() == null) {
            CronUtil.schedule("0 0 * * *", new Task() {
                @Override
                public void execute() {
                    try {
                        service.findNeedMaintenanceToday();
                        log.info("定时扫描维保执行了");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
            CronUtil.start();
        }
    }
}